<?php

namespace App\Repository\Db;

use App\Repository\Contracts\CodeInterface;
use App\Repository\Contracts\MessageInterface;

/**
 * @Author:: HuangYin
 * @DateTime: 2017/6/14 18:24
 */
class CodeRepository extends Repository implements CodeInterface
{

    protected $rules = [
        'created' => [
            'phone' => 'required|regex:/^1[34578][0-9]{9}$/'
        ],
        'checked' => [
            'phone' => 'required|regex:/^1[34578][0-9]{9}$/',
            'code' => 'required'
        ]
    ];

    protected $messages = [
        'phone.required' => '手机号码不能为空',
        'phone.regex' => '手机号码不合法',
        'code.required' => "验证码不能为空"
    ];

    protected function modelName()
    {
        return 'App\Model\Code';
    }

    public function created(array $data)
    {
        $this->validate($data, 'created');
        $data['code'] = mt_rand(100000, 999999);
        if ($this->container->make(MessageInterface::class)->created($data)) {

            // TODO return $this->save($data);
            $this->save($data);

            return $data['code'];
        }

        return 0;
    }

    public function checked($phone, $code)
    {
        $this->validate(['phone' => $phone, 'code' => $code], 'checked');

        return $this->model->where([
            'phone' => $phone,
            'code' => $code,
            'status' => 1])->first();
    }

    public function updateStatus($id)
    {
        return $this->update(['status' => 2], $id, 'id');
    }
}